package com.wn.quality.web;

import com.wn.common.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 全局异常捕获
 * @author wuqingting
 * @date 2022/10/20
 */
@ControllerAdvice("com.wn.quality.web")
@ResponseBody
public class GlobalExceptionHandler {
    //全局其他方法未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity handler(Exception e){
        e.printStackTrace();
        return new ResponseEntity("500","error",null);
    }

    //参数校验异常,用于@Validated(ncrUpdateGroup.class)这样的分组检验抛出的异常(实体类中的数据校验)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult result = e.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();
        HashMap<Object, Object> map = new HashMap<>();
        errors.forEach(error-> map.put(error.getField(),error.getDefaultMessage()));
        return new ResponseEntity("600","参数校验异常",map);
    }
    //方法简单参数校验,类上使用了@Validated,在下方方法参数异常时抛出的异常(不是在实体类中的参数校验)
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity handlerConstraintViolationException(ConstraintViolationException e){
        e.printStackTrace();
        Map<String, String> map = new HashMap<>();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        violations.forEach(f->map.put(f.getPropertyPath().toString(),f.getMessage()));
        return new ResponseEntity<>("600","无效参数",map);
    }

}
